<template>
  <div>
    <!--    搜索表单-->
    <div>
      <el-input style="width: 240px" placeholder="请输入类名" v-model="params.name"></el-input>
      <el-input style="width: 240px; margin-left: 5px" placeholder="请输入作者" v-model="params.author"></el-input>
      <el-input style="width: 240px; margin-left: 5px" placeholder="请输入书号" v-model="params.isbn"></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="load()">
        <i class="el-icon-search"></i> 搜索
      </el-button>
      <el-button style="margin-left: 5px" type="danger" @click="reset">
        <i class="el-icon-refresh"></i>重置
      </el-button>
    </div>
    <!--增删改查-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-edit-outline"></i></el-button>
      <el-button type="danger" @click="delBatch" class="mr-5">批量删除 <i class="el-icon-remove-outline"></i>
      </el-button>
    </div>
    <!--表单内容-->
    <el-table :data="tableData" stripe row-key="id" default-expand-all @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column fixed
                       prop="id"
                       label="编号"
                       width="50">
      </el-table-column>
      <el-table-column prop="name" label="书名"></el-table-column>
      <el-table-column prop="cover" label="封面" width="80">
        <template v-slot="scope">
          <el-image :src="scope.row.cover" :preview-src-list="[scope.row.cover]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="简介" width="200"></el-table-column>
      <el-table-column prop="publishDate" label="出版日期" width="110"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="publisher" label="出版社"></el-table-column>
      <el-table-column prop="category" label="类别" width="130"></el-table-column>
      <el-table-column prop="isbn" label="书号"></el-table-column>
      <el-table-column prop="score" label="书币"></el-table-column>
      <el-table-column prop="counts" label="数量"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="110"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="110"></el-table-column>

      <!--操作-->
      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template v-slot="scope">

          <el-button @click="handleEdit(scope.row)" type="success" size="small">编辑<i class="el-icon-edit"></i>
          </el-button>


          <el-popconfirm
              class="ml-5"
              title="您确定删除这行信息吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" type="danger" size="small">删除 <i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>


    </el-table>

    <!--    分页-->
    <div style="text-align: center; ">
      <el-pagination
          background
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :total="total">
      </el-pagination>
    </div>

    <!--    新增表单-->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="50%" top="0">
      <el-form label-width="80px" style="" :model="form" :rules="rules" ref="rulerForm">

        <el-form-item label="书名" prop="name">
          <el-input v-model="form.name" auto-complete="off" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
              class="avatar-uploader"
              :action="'http://localhost:8888/api/book/file/upload?token=' + this.admin.token"
              :show-file-list="false"
              :on-success="handleCoverSuccess"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="form.description" auto-complete="off" placeholder="请输入简介"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
              v-model="form.publishDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择出版日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" auto-complete="off" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" auto-complete="off" placeholder="请输入出版社"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="category">

          <el-cascader
              :props="{ value: 'name', label: 'name'}"
              v-model="form.categories"
              :options="categories"
              @change="handleChange" style="width: 100%"></el-cascader>

        </el-form-item>


        <el-form-item label="书号" prop="isbn">
          <el-input v-model="form.isbn" auto-complete="off" placeholder="请输入书号"></el-input>
        </el-form-item>


        <el-form-item label="所需书币" prop="score">
          <el-input v-model="form.score" auto-complete="off" placeholder="请输入所需书币"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="counts">
          <el-input v-model="form.counts" auto-complete="off" placeholder="请输入书籍数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


    <!--    //修改-->
    <el-dialog title="用户信息" :visible.sync="updateTab" width="50%" top="0">
      <el-form label-width="80px" style="" :model="updateForm" :rules="rules" ref="rulerForm">

        <el-form-item label="书名" prop="name">
          <el-input v-model="updateForm.name" auto-complete="off" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
              class="avatar-uploader"
              :action="'http://localhost:8888/api/book/file/upload?token=' + this.admin.token"
              :show-file-list="false"
              :on-success="handleCoverSuccess2"
          >
            <img v-if="updateForm.cover" :src="updateForm.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="updateForm.description" auto-complete="off" placeholder="请输入简介"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
              v-model="updateForm.publishDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择出版日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="updateForm.author" auto-complete="off" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="updateForm.publisher" auto-complete="off" placeholder="请输入出版社"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-cascader
              :props="{ value: 'name', label: 'name'}"
              v-model="updateForm.categories"
              :options="categories"
              @change="handleChange" style="width: 100%">
          </el-cascader>
        </el-form-item>
        <el-form-item label="书号" prop="isbn">
          <el-input v-model="updateForm.isbn" auto-complete="off" placeholder="请输入书号"></el-input>
        </el-form-item>
        <el-form-item label="所需书币" prop="score">
          <el-input v-model="updateForm.score" auto-complete="off" placeholder="请输入所需书币"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="counts">
          <el-input v-model="updateForm.counts" auto-complete="off" placeholder="请输入剩余数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelUpdate">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import request from "@/utils/request";
import Cookies from "js-cookie";

export default {
  name: "Category.vue",

  data() {
    const checkCount = (rule, value, callback) => {
      if (!Number.isInteger(parseInt(value))) {
        callback(new Error('请输入数字值'));
      }
      if (parseInt(value) < 0) {
        callback(new Error('请输入合理的书籍数量'));
      }
      callback()
    };


    return {
      admin: Cookies.get('admin') ? JSON.parse(Cookies.get('admin')) : {},
      tableData: [],
      categories: [],
      multipleSelection: [],
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
      },

      dialogFormVisible: false,
      updateTab: false,
      form: {},
      updateForm: {},

      rules: {
        name: [
          {required: true, message: '请输入类名', trigger: 'blur'},
        ],
        score: [
          {required: true, validator: checkCount, triangle: 'blur'}
        ],
        counts: [
          {required: true, validator: checkCount, triangle: 'blur'}
        ],
      },

    }
  },

  created() {
    this.load();
    request.get('/category/tree').then(res => {
      this.categories = res.data
    })
  },


  methods: {
    handleChange() {
    },

    handleCoverSuccess(res) {
      if (res.code === '200') {
        this.$set(this.form, 'cover', res.data)
      }
    },
    handleCoverSuccess2(res) {
      if (res.code === '200') {
        this.$set(this.updateForm, 'cover', res.data)
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)
      request.post("/book/del/batch", ids).then(res => {
        if (res.code === "200") {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      })
    },

    load() {
      request.get('/book/page', {
        params: this.params
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },

    reset() {
      this.params = {
        pageNum: 1,
        pageSize: 10,
      }
      this.load()
    },

    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum
      this.load()
    },

    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
    },

    handleCancel() {
      this.dialogFormVisible = false;
      this.load()
    },

    handleCancelSecond() {
      this.secondTitleTab = false;
      this.load()
    },

    del(id) {
      request.delete('/book/delete/' + id).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
          this.load()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    handleEdit(row) {
      this.updateForm = row;
      this.updateTab = true;
    },


    save() {
      this.$refs['rulerForm'].validate((valid) => {
        if (valid) {
          request.post('/book/save', this.form).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.dialogFormVisible = false
              this.load()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })

    },


    update() {
      this.$refs['rulerForm'].validate((valid) => {
        if (valid) {
          request.put('/book/update', this.updateForm).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.updateTab = false
              this.load()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })

    },
    handleCancelUpdate() {
      this.updateTab = false
      this.load()
    },


  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>